<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\GeneralException;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Repositories\UserLogRepository;
use Illuminate\Support\Facades\Auth;
use App\Repositories\OrderRepository;
use App\Http\Requests\Admin\Order\ShowRequest;
use App\Http\Requests\Admin\Order\QueryResource;
use App\Http\Requests\Admin\Order\OrderCreate;
use App\Http\Requests\Admin\Order\OrderUpdate;
use App\Http\Requests\Admin\Order\OrderDestroy;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class OrderController extends Controller
{
    protected $orderRepository;
    protected $userLogRepository;

    /**
     * OrdersController constructor.
     * @param OrderRepository $orderRepository
     * @param UserLogRepository $userLogRepository
     */
    public function __construct(
        OrderRepository $orderRepository,
        UserLogRepository $userLogRepository
    )
    {
        $this->orderRepository = $orderRepository;
        $this->userLogRepository = $userLogRepository;
    }

    /**
     * 获取订单列表
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $limit = $request->get('paginate', 15);
        $type = $request->get('type', false);
        $status = $request->get('status', false);
        $created_at = $request->get('created_at', false);
        $courier_id = $request->get('courier_id', false);
        $service_id = $request->get('service_id', false);
        $single_number = $request->get('single_number', false);
        if ($limit === null) {
            $limit = 15;
        }
        if ($type === null) {
            $type = false;
        }
        if ($status === null) {
            $status = false;
        }
        if ($created_at === null) {
            $created_at = false;
        }
        if ($courier_id === null) {
            $courier_id = false;
        }
        if ($service_id === null) {
            $service_id = false;
        }
        if ($single_number === null) {
            $single_number = false;
        }
        $orders = $this->orderRepository->getOrders($courier_id, $service_id, $type, $status, $created_at, $limit, $single_number);
        return success($orders);
    }

    /**
     * 根据订单Id 获取订单详情资源
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param ShowRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(ShowRequest $request, $order)
    {
        $res = $this->orderRepository->getOrderDetails($order);
        return success($res);
    }


    /**
     * 新建orders资源
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param OrderCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(OrderCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $orders = $this->orderRepository->addOrder_v2($attributes);
        return stored($orders);
    }

    /**
     * 更新orders资源
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param OrderUpdate $request
     * @param Order $order
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function update(OrderUpdate $request, Order $order)
    {
        $ordersAttr = $request->only([
            'network_id',
            'status',
            'label',
            'type',
            'courier_id'
        ]);
        if (array_key_exists('status', $ordersAttr) && $ordersAttr['status'] == 0) {
            unset($ordersAttr['status']);
        }
        /*
         * 判断订单状态 以及标记情况
         * 2 => 配送中, 3 => 待取件, 4 => 已取件, 5 => 投诉中, 6 => 异常件, 7 => 已退回, 8 => 已退款
         * 标记 拒收 错分 快件状态为6
         * */
        if (array_key_exists('label', $ordersAttr) && $ordersAttr['label'] && $order->status) {
            /*
             * 标记 拒收 错分 快件状态为6
             * */
            if ($order->status < 5) {
                if (in_array($ordersAttr['label'], ['拒收', '错分'])) {
                    $ordersAttr['status'] = 6;
                }
            }
        }
        $order->update($ordersAttr);
        $redis_key = sprintf('GET_ORDER_DETAILS_V1_%d', $order->id);
        Redis::del($redis_key);
        $orders = $this->orderRepository->getOrderDetails($order->id);
        //记录操作日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = 0;
        $name = $admin->name;
        $operation = '修改了订单[' . $order->id . ']';
        $history = json_encode($order->toArray(), true);
        $actuality = json_encode($ordersAttr, true);
        $order_id = $order->id;
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return updated($orders);
    }

    /**
     * 删除 orders 资源
     *
     * Date: 2018/4/10
     * @author Tenny
     * @param OrderDestroy $request
     * @param Order $order
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(OrderDestroy $request, Order $order)
    {
        DB::beginTransaction();
        try {
            $order->delete();
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }

        //记录操作日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = 0;
        $name = $admin->name;
        $operation = '删除了订单[' . $order->id . ']';
        $history = null;
        $actuality = null;
        $order_id = $order->id;
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return deleted();
    }
}
